package cn.lin.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //强制转换方法
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //获取资源请求路径
        String uri = request.getRequestURI();
        //判断是否包含登录相关资源,还有css, js 图片,验证码等资源
        if (uri.contains("/login.jsp") || uri.contains("/loginServlet") || uri.contains("/css/") || uri.contains("/js/") || uri.contains("/fonts/") || uri.contains("/checkCode")) {
            //直接放行
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            //不包含
            Object user = request.getSession().getAttribute("user");
            if (user != null) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                request.setAttribute("login_msg", "您尚未登录,请登录");
                request.getRequestDispatcher("/login.jsp").forward(servletRequest, servletResponse);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
